import { Form, Input, Select } from "antd"
import { useEffect } from "react"
import { ComponentConfig, ComponentSetter, useComponentConfigStore } from "../../../editor/stores/component-config"
import { useComponentStore } from "../../../editor/stores/components"

// 1. 首先渲染 curComponent 基础配置
// 2. 然后渲染组件的配置 setter 属性
export function ComponentAttr() {
    const [form] = Form.useForm()

    const { componentConfigs } = useComponentConfigStore()
    const { curComponent, curComponentId, updateComponentProps } = useComponentStore()

    if (!curComponentId || !curComponent) return null

    // curComponent 变化的时候，把 props 设置到表单用于初始回显数据：
    useEffect(() => {
        const data = form.getFieldsValue()
        form.setFieldsValue({ ...data, ...curComponent.props })
    }, [curComponent])


    function handleValueChange (newProps: ComponentConfig){
        if (curComponentId) {
            updateComponentProps(curComponentId, newProps)
        }
    }

    function renderFormElement(setter: ComponentSetter){
        const { type, options } = setter
        switch (type) {
            case "input":
                return <Input />
            case "number":
                return <Input type="number" />
            case "select":
                return <Select options={options} />
        }
    }

    return (
        <>
            <Form 
                form={form}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 14 }}
                onValuesChange={handleValueChange}
            >
                <Form.Item label="组件ID">
                    <Input value={curComponent.id} disabled />
                </Form.Item>
                <Form.Item label="组件名称">
                    <Input value={curComponent.name} disabled />
                </Form.Item>
                <Form.Item label="组件描述">
                    <Input value={curComponent.desc} disabled />
                </Form.Item>
                {/* 取出 setter 出来渲染 */}
                {
                    componentConfigs[curComponent.name]?.setter?.map((item, index) => (
                        <Form.Item key={item.name} name={item.name} label={item.label}>
                            { renderFormElement(item) }
                        </Form.Item>
                    ))
                }
            </Form>
        </>
    )
}